import React, { useState, useEffect } from "react";
import { useParams, useNavigate } from "react-router-dom";
import axios from "axios";
import { ArticleModel } from "./ArticleModel";
import {api} from "./api/request";

const ArticleView = () => {
    const { id } = useParams();
    const navigate = useNavigate();

    const [article, setArticle] = useState<ArticleModel | null>(null);
    const [loading, setLoading] = useState(true);

    const fetchArticleDetail = async () => {
        setLoading(true);
        try {
            const response = await api.get(`article/get/${id}`);
            setArticle(response.data);
        } catch (error) {
            console.error("获取文章详情失败:", error);
            setArticle(null);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchArticleDetail();
    }, [id]);

    return (
        <div className="min-h-screen bg-gray-50 py-10 px-4">
            {/* 返回按钮 */}
            <button
                onClick={() => navigate("/blogs/page")}
                className="mb-6 flex items-center gap-2 px-4 py-2 bg-gray-800 text-white rounded-lg hover:bg-gray-700 transition"
            >
                ← 返回列表
            </button>

            {/* 加载状态 */}
            {loading && (
                <div className="text-center py-10 text-lg text-gray-600">
                    加载中...
                </div>
            )}

            {/* 文章内容 */}
            {!loading && article && (
                <div className="max-w-4xl mx-auto bg-white p-8 rounded-xl shadow-md border border-gray-100">
                    {/* 标题 */}
                    <h1 className="text-3xl font-bold mb-4 text-gray-900">
                        {article.articleName}
                    </h1>

                    {/* 元信息 */}
                    <div className="text-gray-500 text-sm mb-6 space-y-1">
                        <p>文章 ID：{article.id}</p>
                        <p>作者：{article.author}</p>
                        <p>创建时间：{article.createTime}</p>
                        <p>更新时间：{article.updateTime}</p>
                    </div>

                    <hr className="my-6" />

                    {/* 内容 */}
                    <div className="prose prose-lg prose-gray leading-relaxed whitespace-pre-wrap">
                        {article.content}
                    </div>
                </div>
            )}

            {/* 无数据 */}
            {!loading && !article && (
                <div className="text-center text-gray-500 text-lg py-20">
                    ❌ 文章不存在或加载失败
                </div>
            )}
        </div>
    );
};

export default ArticleView;
